import config from '../config.js';

/*导航菜单白名单*/
const tabBarLinks = [
	'/pages/index/index',
	'/pages/product/category',
	'/pages/shop/middle',
	'/pages/cart/cart',
	'/pages/user/index/index'
];

/*分享页面,扫码白名单*/
const shareLinks = [
	'/pages/plus/assemble/fight-group-detail/fight-group-detail',
	'/pages/plus/bargain/haggle/haggle',
	'/pages/user/invite/invite',
];

/**
 * 页面跳转
 * @param {string} url - 跳转地址
 * @param {string} type - 跳转类型: redirect / reLaunch / navigateTo
 */
export const gotopage = (url, type) => {
	console.log(url)
	if (!url) return;

	if (!url.startsWith('/')) url = '/' + url;

	// 提取 path 和 query
	let [path, queryStr] = url.split('?');
	queryStr = queryStr ? queryStr + '&' : '';
	queryStr += 'app_id=' + config.app_id;

	// #ifdef H5
	// hash 路由处理，确保最终格式 /h5/#/pages/...
	const h5Prefix = config.h5_addr ? config.h5_addr.replace(/\/$/, '') : ''; // 去掉末尾 /
	if (!path.startsWith('/#/')) {
		path = path.startsWith('/') ? '/#' + path : '/#/' + path;
	}

	const finalUrl = h5Prefix + path + '?' + queryStr;
	const hashUrl = url.split('?')[0] + '?' + queryStr

	console.log(hashUrl)
	// H5 分享页面
	const sharePath = path.replace('/#', '');
	// if (shareLinks.includes(sharePath)) {
	// 	window.location.hash = hashUrl;
	// 	return;
	// }

	// tabBar 页面
	const diyTabBarLinks = uni.getStorageSync('TabBar')?.list || [];
	const isTabBar = tabBarLinks.includes(sharePath) || diyTabBarLinks.some(item => item.link_url === sharePath);
	if (isTabBar) {
		// H5 hash 跳转用 replace
		// window.location.hash = hashUrl;
		// window.location.hash = hashUrl;
		uni.switchTab({
			url: hashUrl
		})
		// window.location = finalUrl
		// window.open(finalUrl)
		// window.location.replace(finalUrl)
		return;
	}

	// 普通页面跳转
	// window.location.hash = hashUrl;

	uni.navigateTo({
		url: hashUrl
	})

	return;

	// #endif

	// 非 H5 小程序内部跳转
	const p = url.split('?')[0];
	const diyTabBarLinksNative = uni.getStorageSync('TabBar')?.list || [];
	const isTabBarNative = tabBarLinks.includes(p) || diyTabBarLinksNative.some(item => item.link_url === p);

	if (isTabBarNative) {
		uni.reLaunch({
			url
		});
		return;
	}

	if (process.env.NODE_ENV === 'production' && shareLinks.includes(p)) {
		uni.navigateTo({
			url
		});
		return;
	}

	switch (type) {
		case 'redirect':
			uni.redirectTo({
				url
			});
			break;
		case 'reLaunch':
			uni.reLaunch({
				url
			});
			break;
		default:
			uni.navigateTo({
				url
			});
	}
};